#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time     :2021/01/10
# @Author   :Changshu
# @File     :Exercise_661.py

# 661. 图片平滑器
# 包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ，
# 平均灰度的计算是周围的8个单元和它本身的值求平均，如果周围的单元格不足八个，则尽可能多的利用它们。

# [(i-1,j-1) (i-1,j) (i-1,j+1)]
# [(i  ,j-1) (i , j) (i  ,j+1)]
# [(i+1,j-1) (i+1,j) (i+1,j+1)]
class Solution:
	'''法一：设置一个滑动窗口,sb代码，写错了也就罢了，还写的很难看

	def imageSmoother(self, M: list) -> list:
		row, column = len(M), len(M[0])
		i, j = 0, 0
		res = []
		while i < row:
			r = []
			s = 0
			count = 1
			while j < column:
				s += M[i][j]
				if i - 1 >= 0:
					s+=M[i - 1][j]
					count += 1
					if j - 1 >= 0:
						s += M[i][j - 1]
						s += M[i - 1][j - 1]
						count += 2
					if j + 1 < column:
						s += M[i][j + 1]
						s += M[i - 1][j + 1]
						count += 2
				if i + 1 < row:
					s += M[i + 1][j]
					count += 1
					if j - 1 >= 0:
						s += M[i + 1][j - 1]
						count += 1
					if j + 1 < column:
						s += M[i + 1][j + 1]
						count += 1
				r.append(s // count)
				j += 1
			res.append(r)
			i += 1
		return res
'''


	'''nb'''
	def imageSmoother(self, M: list) -> list:
		R,C=len(M),len(M[0])
		ans=[[0]*C for _ in M]

		for r in range(R):
			for c in range(C):
				count=0
				for nr in (r-1,r,r+1):
					for nc in (c-1,c,c+1):
						if 0<=nr<R and 0<=nc<C:
							ans[r][c]+=M[nr][nc]
							count+=1
				ans[r][c]=ans[r][c]//count
		return ans

if __name__ == '__main__':
	solution=Solution()
	# M=[[1,1,1],[1,0,1],[1,1,1]]
	# M=[[145,124,76,213,34],[123,78,84,167,213],[190,128,160,124,178],[215,210,167,156,134],[190,123,145,178,162]]
	M=[[2,3,4],[5,6,7],[8,9,10],[11,12,13],[14,15,16]]
	print(solution.imageSmoother(M))
